// 服务器配置
const SERVER_URL = 'http://localhost:5001';

// 游戏状态管理
let gameState = {
    user: null,
    socket: null,
    gameId: null,
    isInQueue: false,
    opponentName: '',
    selfProgress: 0,
    opponentProgress: 0,
    totalQuestions: 10,
    isMyTurn: false
};

// DOM元素缓存
const authScreen = document.getElementById('auth-screen');
const userScreen = document.getElementById('user-screen');
const waitingScreen = document.getElementById('waiting-screen');
const countdownScreen = document.getElementById('countdown-screen');
const gameScreen = document.getElementById('game-screen');
const endScreen = document.getElementById('end-screen');
const disconnectModal = document.getElementById('disconnect-modal');

// 切换标签页
function switchTab(tabName) {
    const loginTab = document.getElementById('login-tab');
    const registerTab = document.getElementById('register-tab');
    const loginForm = document.getElementById('login-form');
    const registerForm = document.getElementById('register-form');
    
    if (tabName === 'login') {
        loginTab.classList.add('active');
        registerTab.classList.remove('active');
        loginForm.classList.add('active');
        registerForm.classList.remove('active');
    } else {
        loginTab.classList.remove('active');
        registerTab.classList.add('active');
        loginForm.classList.remove('active');
        registerForm.classList.add('active');
    }
    
    // 清除消息
    document.getElementById('login-message').textContent = '';
    document.getElementById('register-message').textContent = '';
}

// 注册函数
function register() {
    const username = document.getElementById('register-username').value.trim();
    const password = document.getElementById('register-password').value;
    const message = document.getElementById('register-message');
    
    if (!username || !password) {
        message.textContent = '请输入用户名和密码';
        return;
    }
    
    fetch(`${SERVER_URL}/api/register`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        message.textContent = data.message;
        if (data.success) {
            // 注册成功后自动切换到登录标签
            switchTab('login');
            document.getElementById('login-username').value = username;
            document.getElementById('login-password').focus();
        }
    })
    .catch(error => {
        message.textContent = '注册失败，请重试';
        console.error('注册错误:', error);
    });
}

// 登录函数
function login() {
    const username = document.getElementById('login-username').value.trim();
    const password = document.getElementById('login-password').value;
    const message = document.getElementById('login-message');
    
    if (!username || !password) {
        message.textContent = '请输入用户名和密码';
        return;
    }
    
    fetch(`${SERVER_URL}/api/login`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
    })
    .then(response => response.json())
    .then(data => {
        message.textContent = data.message;
        if (data.success) {
            // 保存用户信息
            gameState.user = data.user;
            
            // 更新UI
            updateUserScreen();
            
            // 切换到用户界面
            authScreen.style.display = 'none';
            userScreen.style.display = 'block';
            
            // 初始化WebSocket连接
            initSocket();
        }
    })
    .catch(error => {
        message.textContent = '登录失败，请重试';
        console.error('登录错误:', error);
    });
}

// 登出函数
function logout() {
    // 关闭WebSocket连接
    if (gameState.socket) {
        gameState.socket.disconnect();
        gameState.socket = null;
    }
    
    // 重置游戏状态
    gameState = {
        user: null,
        socket: null,
        gameId: null,
        isInQueue: false,
        opponentName: '',
        selfProgress: 0,
        opponentProgress: 0,
        totalQuestions: 10,
        isMyTurn: false
    };
    
    // 清除表单
    document.getElementById('login-username').value = '';
    document.getElementById('login-password').value = '';
    document.getElementById('register-username').value = '';
    document.getElementById('register-password').value = '';
    document.getElementById('login-message').textContent = '';
    document.getElementById('register-message').textContent = '';
    
    // 切换到登录界面
    userScreen.style.display = 'none';
    authScreen.style.display = 'block';
}

// 更新用户界面信息
function updateUserScreen() {
    document.getElementById('user-name').textContent = gameState.user.username;
    document.getElementById('user-points').textContent = gameState.user.points;
    
    // 加载排行榜数据
    loadLeaderboard();
    // 加载用户排名信息
    loadUserRankInfo();
}

// 切换排行榜标签页
function showLeaderboardTab(tabName) {
    // 隐藏所有内容
    document.getElementById('top40-leaderboard').classList.remove('active');
    document.getElementById('my-rank-detail').classList.remove('active');
    
    // 移除所有按钮的活动状态
    document.getElementById('show-top40-btn').classList.remove('active');
    document.getElementById('show-my-rank-btn').classList.remove('active');
    
    // 显示选中的内容
    if (tabName === 'top40') {
        document.getElementById('top40-leaderboard').classList.add('active');
        document.getElementById('show-top40-btn').classList.add('active');
    } else if (tabName === 'myRank') {
        document.getElementById('my-rank-detail').classList.add('active');
        document.getElementById('show-my-rank-btn').classList.add('active');
    }
}

// 加载排行榜数据
function loadLeaderboard() {
    const leaderboardList = document.getElementById('leaderboard-list');
    leaderboardList.innerHTML = '<div class="loading">加载中...</div>';
    
    fetch(`${SERVER_URL}/api/leaderboard?limit=40`)
        .then(response => {
            // 检查响应状态
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            
            // 检查响应类型是否为JSON
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                console.warn('响应不是JSON格式，尝试解析');
            }
            
            return response.json();
        })
        .then(data => {
            if (data.success) {
                leaderboardList.innerHTML = '';
                
                data.leaderboard.forEach(player => {
                    const item = document.createElement('div');
                    item.className = `leaderboard-item ${player.id === gameState.user.id ? 'current-user' : ''}`;
                    
                    // 为前三名添加特殊样式
                    const rankClass = player.rank <= 3 ? 'rank-number top3' : 'rank-number';
                    
                    item.innerHTML = `
                        <div class="rank-col">
                            <span class="${rankClass}">${player.rank}</span>
                        </div>
                        <div class="name-col">
                            <span class="player-name">${player.username}</span>
                        </div>
                        <div class="points-col">
                            <span class="player-points">${player.points}</span>
                        </div>
                    `;
                    
                    leaderboardList.appendChild(item);
                });
            } else {
                leaderboardList.innerHTML = '<div class="error">加载失败，请重试</div>';
            }
        })
        .catch(error => {
            console.error('加载排行榜失败:', error);
            leaderboardList.innerHTML = '<div class="error">加载失败，请检查网络连接</div>';
        });
}

// 加载用户排名信息
function loadUserRankInfo() {
    // 加载用户基本排名信息
    fetch(`${SERVER_URL}/api/user/${gameState.user.id}/rank`)
        .then(response => {
            // 检查响应状态
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            
            // 检查响应类型是否为JSON
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                console.warn('响应不是JSON格式，尝试解析');
            }
            
            return response.json();
        })
        .then(data => {
            if (data.success) {
                const user = data.user;
                // 更新用户排名显示
                document.getElementById('user-rank').textContent = user.rank;
                document.getElementById('my-rank-number').textContent = user.rank;
                document.getElementById('my-username').textContent = user.username;
                document.getElementById('my-total-points').textContent = user.points;
                document.getElementById('my-position').textContent = `第 ${user.rank} 名`;
                
                // 加载相邻玩家数据
                loadNeighborPlayers(user.rank);
            } else {
                document.getElementById('user-rank').textContent = '--';
                console.error('获取用户排名失败:', data.message);
            }
        })
        .catch(error => {
            console.error('获取用户排名失败:', error);
            document.getElementById('user-rank').textContent = '--';
        });
}

// 加载相邻玩家数据
function loadNeighborPlayers(userRank) {
    const neighborsList = document.getElementById('neighbors-list');
    neighborsList.innerHTML = '<div class="loading">加载中...</div>';
    
    // 获取前后各5名玩家（如果有的话）
    const startRank = Math.max(1, userRank - 5);
    const endRank = userRank + 5;
    
    fetch(`${SERVER_URL}/api/leaderboard?limit=${endRank}`)
        .then(response => {
            // 检查响应状态
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
            
            // 检查响应类型是否为JSON
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                console.warn('响应不是JSON格式，尝试解析');
            }
            
            return response.json();
        })
        .then(data => {
            if (data.success) {
                neighborsList.innerHTML = '';
                
                // 过滤出相邻玩家
                const neighborPlayers = data.leaderboard.filter(player => 
                    player.rank >= startRank && player.rank <= endRank && player.id !== gameState.user.id
                );
                
                if (neighborPlayers.length > 0) {
                    neighborPlayers.forEach(player => {
                        const item = document.createElement('div');
                        item.className = 'neighbor-item';
                        
                        // 根据排名与用户的关系显示提示
                        let rankDiff = '';
                        if (player.rank < gameState.user.rank) {
                            rankDiff = '↑ ' + (gameState.user.rank - player.rank) + ' 名';
                        } else {
                            rankDiff = '↓ ' + (player.rank - gameState.user.rank) + ' 名';
                        }
                        
                        item.innerHTML = `
                            <div class="rank-info">
                                <div class="rank-number">${player.rank}</div>
                                <div class="player-name">${player.username}</div>
                            </div>
                            <div class="points-info">
                                <div class="player-points">${player.points}</div>
                                <div class="rank-diff">${rankDiff}</div>
                            </div>
                        `;
                        
                        neighborsList.appendChild(item);
                    });
                } else {
                    neighborsList.innerHTML = '<div class="no-neighbors">暂无相邻玩家数据</div>';
                }
            } else {
                neighborsList.innerHTML = '<div class="error">加载失败，请重试</div>';
            }
        })
        .catch(error => {
            console.error('加载相邻玩家失败:', error);
            neighborsList.innerHTML = '<div class="error">加载失败，请检查网络连接</div>';
        });
}

// 初始化WebSocket连接
function initSocket() {
    // 连接到WebSocket服务器
    gameState.socket = io(SERVER_URL);
    
    // 连接事件
    gameState.socket.on('connect', () => {
        console.log('WebSocket连接成功');
    });
    
    // 断开连接事件
    gameState.socket.on('disconnect', () => {
        console.log('WebSocket连接断开');
        gameState.isInQueue = false;
    });
    
    // 匹配成功事件
    gameState.socket.on('match_found', (data) => {
        gameState.isInQueue = false;
        gameState.gameId = data.game_id;
        gameState.opponentName = data.opponent_name;
        
        // 更新UI
        document.getElementById('opponent-name').textContent = gameState.opponentName;
        waitingScreen.style.display = 'none';
        countdownScreen.style.display = 'block';
    });
    
    // 倒计时事件
    gameState.socket.on('countdown', (data) => {
        document.getElementById('countdown-number').textContent = data.seconds;
    });
    
    // 游戏开始事件
    gameState.socket.on('game_start', (data) => {
        // 移除isMyTurn，因为双方同时答题
        gameState.selfProgress = data.your_progress;
        gameState.opponentProgress = data.opponent_progress;
        gameState.totalQuestions = data.total_questions;
        
        // 更新UI
        updateGameUI(data);
        countdownScreen.style.display = 'none';
        gameScreen.style.display = 'block';
    });
    
    // 游戏状态更新事件
    gameState.socket.on('game_update', (data) => {
        // 移除isMyTurn，因为双方同时答题
        gameState.selfProgress = data.your_progress;
        gameState.opponentProgress = data.opponent_progress;
        
        // 更新UI
        updateGameUI(data);
    });
    
    // 答案反馈事件
    gameState.socket.on('answer_feedback', (data) => {
        const feedback = document.getElementById('game-feedback');
        if (data.correct) {
            feedback.className = 'feedback correct';
            feedback.textContent = '正确！太棒了！';
        } else {
            feedback.className = 'feedback incorrect';
            feedback.textContent = data.message;
        }
        
        // 3秒后隐藏反馈
        setTimeout(() => {
            feedback.className = 'feedback';
        }, 3000);
    });
    
    // 游戏结束事件
    gameState.socket.on('game_over', (data) => {
        // 更新UI
        document.getElementById('result-title').textContent = data.is_winner ? '恭喜获胜！' : '游戏结束';
        document.getElementById('winner-message').textContent = data.is_winner ? '你赢得了比赛！' : `恭喜${data.winner}赢得了比赛！`;
        document.getElementById('your-final-progress').textContent = data.your_progress;
        document.getElementById('opponent-final-progress').textContent = data.opponent_progress;
        document.getElementById('points-gained').textContent = data.points_gained;
        
        // 更新用户积分
        if (gameState.user) {
            gameState.user.points += data.points_gained;
        }
        
        // 切换到结束界面
        gameScreen.style.display = 'none';
        endScreen.style.display = 'block';
    });
    
    // 对手断开连接事件 - 直接返回匹配页面
    gameState.socket.on('opponent_disconnected', () => {
        // 重置游戏状态
        gameState.gameId = null;
        gameState.isInQueue = false;
        gameState.opponentName = '';
        gameState.selfProgress = 0;
        gameState.opponentProgress = 0;
        
        // 隐藏游戏相关界面，显示用户匹配页面
        gameScreen.style.display = 'none';
        waitingScreen.style.display = 'none';
        countdownScreen.style.display = 'none';
        endScreen.style.display = 'none';
        disconnectModal.style.display = 'none';
        
        // 显示用户界面，让用户可以重新匹配
        userScreen.style.display = 'block';
        
        // 显示提示信息
        const message = document.getElementById('user-message');
        if (message) {
            message.textContent = '对手已退出游戏，请重新匹配';
            setTimeout(() => {
                message.textContent = '';
            }, 3000);
        }
    });
}

// 查找对手
function findMatch() {
    if (!gameState.socket || !gameState.user) return;
    
    const grade = document.getElementById('multiplayer-grade').value;
    
    // 发送加入队列请求
    gameState.socket.emit('join_queue', {
        user_id: gameState.user.id,
        username: gameState.user.username,
        grade: parseInt(grade)
    });
    
    gameState.isInQueue = true;
    
    // 切换到等待界面
    userScreen.style.display = 'none';
    waitingScreen.style.display = 'block';
}

// 取消匹配
function cancelMatch() {
    if (!gameState.socket || !gameState.isInQueue) return;
    
    // 发送离开队列请求
    gameState.socket.emit('leave_queue');
    gameState.isInQueue = false;
    
    // 返回用户界面
    waitingScreen.style.display = 'none';
    userScreen.style.display = 'block';
}

// 更新游戏UI
function updateGameUI(data) {
    // 更新对手信息
    document.getElementById('game-opponent-name').textContent = data.opponent_name || gameState.opponentName;
    document.getElementById('total-questions').textContent = gameState.totalQuestions;
    
    // 更新进度
    document.getElementById('self-progress-text').textContent = gameState.selfProgress;
    document.getElementById('opponent-progress-text').textContent = gameState.opponentProgress;
    document.getElementById('self-progress-bar').style.width = `${(gameState.selfProgress / gameState.totalQuestions) * 100}%`;
    document.getElementById('opponent-progress-bar').style.width = `${(gameState.opponentProgress / gameState.totalQuestions) * 100}%`;
    
    // 更新回合指示器 - 双方同时答题
    const turnIndicator = document.getElementById('turn-indicator');
    const turnMessage = document.getElementById('turn-message');
    
    // 双方都可以答题，始终显示题目和启用输入
    turnIndicator.className = 'turn-indicator your-turn';
    turnMessage.textContent = '同时答题，加油！';
    document.getElementById('game-question').textContent = data.question;
    document.getElementById('game-answer').disabled = false;
    document.getElementById('submit-btn').disabled = false;
    document.getElementById('game-answer').focus();
    
    // 清空输入框和反馈
    document.getElementById('game-answer').value = '';
    document.getElementById('game-feedback').className = 'feedback';
}

// 提交答案 - 双方都可以随时提交
function submitGameAnswer() {
    const answer = document.getElementById('game-answer').value.trim();
    
    if (!answer || !gameState.socket) return;
    
    // 发送答案到服务器
    gameState.socket.emit('submit_answer', {
        game_id: gameState.gameId,
        answer: answer
    });
    
    // 在同时答题模式下，不禁用按钮，允许用户继续提交
    // 清空输入框，方便用户重新输入
    document.getElementById('game-answer').value = '';
    document.getElementById('game-answer').focus();
}

// 再来一局
function playAgain() {
    endScreen.style.display = 'none';
    findMatch();
}

// 返回主界面
function backToUserScreen() {
    // 刷新用户积分
    if (gameState.user) {
        fetch(`${SERVER_URL}/api/user/${gameState.user.id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                gameState.user.points = data.user.points;
                updateUserScreen();
            }
        });
    }
    
    endScreen.style.display = 'none';
    userScreen.style.display = 'block';
}

// 关闭断开连接模态框
function closeDisconnectModal() {
    disconnectModal.style.display = 'none';
    backToUserScreen();
}

// 监听回车键提交答案
document.getElementById('game-answer').addEventListener('keypress', function(e) {
    if (e.key === 'Enter' && !this.disabled) {
        submitGameAnswer();
    }
});

// 监听页面卸载，清理WebSocket连接
window.addEventListener('beforeunload', () => {
    if (gameState.socket) {
        gameState.socket.disconnect();
    }
});